package git.soulbgm.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import git.soulbgm.common.base.BaseController;
import git.soulbgm.common.handler.AlarmExcelDictHandlerImpl;
import git.soulbgm.common.pojo.QueryDto;
import git.soulbgm.common.pojo.Response;
import git.soulbgm.pojo.AlarmInfo;
import git.soulbgm.service.AlarmInfoService;
import git.soulbgm.utils.EasyPoiUtil;
import git.soulbgm.utils.StringUtil;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

import static git.soulbgm.common.MonitorConstants.*;

/**
 * 服务控制器
 *
 * @author SoulBGM
 * @date 2022/03/11 10:28
 */
@RestController
@RequestMapping("system/alarm")
public class AlarmController extends BaseController {

    private final AlarmInfoService alarmInfoService;
    private final AlarmExcelDictHandlerImpl dictHandler;

    public AlarmController(AlarmInfoService alarmInfoService, AlarmExcelDictHandlerImpl dictHandler) {
        this.alarmInfoService = alarmInfoService;
        this.dictHandler = dictHandler;
    }

    /**
     * 查看告警信息列表
     *
     * @param dto       查询信息
     * @param queryPage 查询页面参数
     * @return {@link Page}<{@link AlarmInfo}>
     */
    @PostMapping("list")
    public Response list(@RequestBody QueryDto<AlarmInfo> dto, Page<AlarmInfo> queryPage) {
        boolean flag = dto.getStartTime() != null && dto.getEndTime() != null;
        SFunction<AlarmInfo, Object> function = AlarmInfo::getCreateTime;
        Page<AlarmInfo> resultPage = alarmInfoService.page(queryPage, new LambdaQueryWrapper<>(dto.getData())
                .between(flag, function, dto.getStartTime(), dto.getEndTime()));
        return success(resultPage);
    }

    /**
     * 导出告警信息
     *
     * @param info      查询信息
     * @param beginTime 开始时间
     * @param endTime   结束时间
     * @param response  响应
     */
    @GetMapping("export")
    public void export(AlarmInfo info, String beginTime, String endTime, HttpServletResponse response) {
        boolean flag = beginTime != null && endTime != null && StringUtil.isNotEmpty(beginTime, endTime);
        List<AlarmInfo> list = alarmInfoService.list(new LambdaQueryWrapper<>(info)
                .between(flag, AlarmInfo::getCreateTime, beginTime, endTime));
        try {
            EasyPoiUtil.exportExcel(response, "告警数据", list, AlarmInfo.class, dictHandler);
        } catch (IOException e) {
            throw new RuntimeException("导出失败");
        }
    }

    /**
     * 添加告警信息
     *
     * @param info 信息
     * @return {@link Response}
     */
    @PostMapping("add")
    public Response add(AlarmInfo info) {
        boolean result = alarmInfoService.save(info);
        return result ? success() : error();
    }

    /**
     * 删除告警信息
     *
     * @param ids 多个id以逗号隔开
     * @return {@link Response}
     */
    @PostMapping("remove")
    public Response remove(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        long count = alarmInfoService.listByIds(idList).stream().filter(o -> o.getArtificialHandle() == HANDLE_COMPLETE).count();
        if (count != idList.size()) {
            return error("请先处理告警内容再进行删除");
        }
        boolean result = alarmInfoService.removeByIds(idList);
        return result ? success() : error();
    }

    /**
     * 处理告警
     *
     * @param ids               多个id以逗号隔开
     * @param artificialMessage 处理留言
     * @return {@link Response}
     */
    @PostMapping("handle")
    public Response edit(String ids, String artificialMessage) {
        List<String> idList = Arrays.asList(ids.split(","));
        AlarmInfo info = new AlarmInfo();
        info.setArtificialHandle(HANDLE_COMPLETE);
        info.setArtificialHandleTime(System.currentTimeMillis());
        info.setArtificialMessage(artificialMessage);
        boolean result = alarmInfoService.update(info, new LambdaQueryWrapper<AlarmInfo>()
                .eq(AlarmInfo::getMachineHandle, HANDLE_COMPLETE)
                .in(AlarmInfo::getId, idList));
        return result ? success() : error();
    }

    /**
     * 查看告警计数
     *
     * @return {@link Response}
     */
    @GetMapping("selectAlarmCount")
    public Response selectAlarmCount() {
        return success(alarmInfoService.getAlarmCountVo());
    }

}
